<?php

namespace app\web\controller;

use app\common\controller\Frontend;
use app\common\model\goods\Goods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\Storehouse;
use app\common\model\supplier\Supplier;
use think\Cache;
use think\Config;
use think\Db;
use think\Exception;
use think\Hook;
use think\Validate;
use app\common\model\purchase\Order;


class Wweixin extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    protected $corpid = null;
    protected $corpsecret = null;
    protected $token = null;
    protected $tem = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->corpid = 'wwb5bb483b56206435';
        $this->corpsecret = 'cDF6PnpbUxZvr5E5vkPNajmShxcE7JZAcM9gCKerHcM';
        $this->token = Cache::get('token');
        if(empty($this->token)){
            $this->gettoken();
        }

    }
    /*
     * 获取token
     */
    public function gettoken(){
        $data = array(
          'corpid'=>$this->corpid,
          'corpsecret'=>$this->corpsecret,
        );
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken';
        $res = curl_get($url,$data);
        if(!empty($res)){
            $json = json_decode($res,true);
            if($json['errcode'] == 0){
                Cache::set('token',$json['access_token'],7000);
            }
        }
    }
    public function getcode(){
        if (isRequestSecure()){
            $prefix =  'https';
        }else{
            $prefix =  "http";
        }

        $redirect_uri = $prefix.'://'.$_SERVER['SERVER_NAME'].'/web/wweixin/getuid';
        $data = array(
            'appid'=>$this->corpid,
            'redirect_uri'=>urlencode($redirect_uri),
            'response_type'=>'code',
            'scope'=>'snsapi_base',
            'state'=>'#wechat_redirect',
        );
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
        if(!empty($data)){
            $str = '';
            foreach ($data as $k=> $v){
                $str .= $k.'='.$v.'&';
            }
            $str = substr($str,0,strlen($str)-1);;
            $url .='?'.$str;
        }

        $this->redirect($url);
    }
    public function getuid(){
        $params = input();
//        dump($params);
        if(isset($params['code']) && !empty($params['code'])){
            $data = array(
              'access_token'=>$this->token,
              'code'=>$params['code'],
            );
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo';
            $res = curl_get($url,$data);
//            dump($res);
            if(!empty($res)){
                $res = json_decode($res,true);
//                dump($res);
                if($res['errcode'] == 0){
                    $UserId = $res['UserId'];
                    $row = Db::name('user')->where(array('userid'=>$UserId))->find();
                    if(empty($row)){
                        $uid = Db::name('user')->insertGetId(array(
                           'userid'=>$UserId,
                            'createtime'=>time(),
                            'logintime'=>time(),
                        ));
                    }else{
                        Db::name('user')->where(array('id'=>$row['id']))->update(array(
                            'logintime'=>time(),
                        ));
                        $uid = $row['id'];
                    }
//                    dump($uid);
                    if($uid){
                        session('user_id',$uid);
                        $bin = Db::name('user_binding')
                            ->alias('u')
                            ->where(array('user_id'=>$uid,'is_default'=>1))
                            ->join('admin a','u.admin_id = a.id')
                            ->find();
//                        dump($bin);
                        if(empty($bin)){
                            $this->redirect('/web/users/login');
                        }else{
                            session('admin',Db::name('admin')->where(array('id'=>$bin['admin_id']))->find());
                            $this->redirect(session('url'));
                        }
                    }
                }
            }
        }
    }
    public function sendmessage(){
        $data = array(
          'touser'=>'GuiGui',
//          'toparty'=>'@all',
//          'totag'=>'@all',
          'msgtype'=>'textcard',
          'agentid'=>1000003,
          'textcard'=>array(
              'title'=>'领奖通知',
              'description'=>"你中奖了",
              'url'=>'URL',
              'btntxt'=>'更多',
          ),
          'enable_id_trans'=>0,
          'enable_duplicate_check'=>0,
          'duplicate_check_interval'=>1800,
        );
//        dump($data);
//        exit;
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$this->token;
        $res =curl_post($url,json_encode($data,JSON_UNESCAPED_UNICODE));
        dump(json_decode($res,true));
    }
    public function senmsg($type=null){
        $host = $_SERVER['HTTP_HOST'];
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $tem = array(
          2=>array(
            'title'=>'采购入库单创建通知',
            'controller'=>$protocol.$host.'/web/enter/index',
            'description'=>'创建了一个采购入库单',
          ),
          6=>array(
            'title'=>'销售单创建通知',
            'controller'=>$protocol.$host.'/web/sales/index',
            'description'=>'创建了一个销售单',
          ),
          7=>array(
            'title'=>'销售出库单创建通知',
            'controller'=>$protocol.$host.'/web/checkout/index',
            'description'=>'创建了一个销售出库单',
          ),
          12=>array(
            'title'=>'厂家直发创建通知',
            'controller'=>$protocol.$host.'/web/factory/index',
            'description'=>'创建了一个厂家直发单',
          ),
        );
        if(empty($type)){
            return false;
        }
        $tel = $tem[$type];
        $users = Db::name('user')
            ->alias('u')
            ->join('user_binding b','u.id = b.user_id')
            ->where(array('admin_id'=>1))
            ->select();
        $tousers = [];
        foreach ($users as $v){
            $tousers[] = $v['userid'];
        }


        $data = array(
            'touser'=>implode('|',$tousers),
//          'toparty'=>'@all',
//          'totag'=>'@all',
            'msgtype'=>'textcard',
            'agentid'=>1000003,
            'textcard'=>array(
                'title'=>$tel['title'],
                'description'=>$tel['description'],
                'url'=>$tel['controller'],
                'btntxt'=>'更多',
            ),
            'enable_id_trans'=>0,
            'enable_duplicate_check'=>0,
            'duplicate_check_interval'=>1800,
        );

        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='.$this->token;
        curl_post($url,json_encode($data,JSON_UNESCAPED_UNICODE));
    }
}
